package com.share.example.selenium.service.alibaba.buy;

import com.alibaba.fastjson.JSON;
import com.share.common.exceptions.RobotOperateException;
import com.share.common.exceptions.UnFindTargetException;
import com.share.common.utils.DateUtil;
import com.share.common.utils.DelayUtil;
import com.share.common.utils.DingDingUtil;
import com.share.example.selenium.service.AbsDriver;
import com.share.example.selenium.utils.DriverUtil;
import com.share.example.selenium.utils.ElementUtil;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Led table lamp 50次
 * Table light 20次
 * Shenzhen founder industrial Co.ltd
 */

@Data
@Slf4j
@Service
public class AlibabaClickGridBoxService extends AbsDriver {
    private final String ALIBABA_URL_PRE = "https://www.alibaba.com";
    private final String SEARCH_SUCCESS_FORWORD_URL_PRE = "https://www.alibaba.com/trade/search?";

    @Autowired
    protected WebDriver driver;

    @Override
    public void reInitDriver(WebDriver driver) {
        this.driver = driver;
    }

    //批量访问
    public Map<String, Object> batchClickGrid(int clickNum, String keyWord, String companyName) {
        int success = 0;
        int errCount = 0;
        String errMsg = "";
        String startTime = DateUtil.getDateTime();
        int i = 1;
        for (; i <= clickNum; i++) {
            try {
                clickGrid(keyWord, companyName);
                success++;
                errCount = 0; //清零
                log.info("第{}次点击访问成功", i);
            } catch (RobotOperateException e1) {
                log.error("第{}次操作,发现机器人操作", i, e1);
                errCount = 9999;
                errMsg = e1.getMessage();
            } catch (UnFindTargetException e2) {
                errCount++;
                log.error("第{}次操作,属性没找到", i, e2);
                errMsg = e2.getMessage();
            } catch (Exception e3) {
                errCount++;
                log.error("第{}次操作,执行异常", i, e3);
                errMsg = e3.getMessage();
            }

            //发送消息
            String context = errCount == 0 ? "成功" : "失败";
            context = keyWord + "_" + DateUtil.getDateTime() + "_" + i + "_" + context + errMsg;
            DingDingUtil.sendMdMsg(keyWord, context);

            if (errCount >= 3) {
                log.error("连续多次异常终止任务");
                break;
            }
        }

        Map<String, Object> reMap = new HashMap<>();
        reMap.put("访问成功次数", success);
        reMap.put("已访问次数", i);
        reMap.put("目标次数", clickNum);
        reMap.put("keyWord", keyWord);
        reMap.put("companyName", companyName);
        reMap.put("startTime", startTime);

        DingDingUtil.sendMdMsg(keyWord, "汇总:" + JSON.toJSONString(reMap));

        return reMap;
    }

    //一次点击
    public Long clickGrid(String keyWord, String companyName) {
        long startTime = System.currentTimeMillis();

        //1.打开门户网站首页
        log.info("正在打开网址={}", ALIBABA_URL_PRE);
        driver.get(ALIBABA_URL_PRE);
        DelayUtil.sleepRangMillis(800, 1500);
        String sessionId = DriverUtil.getWindow(driver);
        String[] sessionIds = DriverUtil.listWindows2Array(driver);

        //2.查找输入框
        log.info("正向搜索框中输入keyword={}", keyWord);
        WebElement inputEle = driver.findElement(By.xpath("//*[@id=\"root\"]/div[1]/div[2]/div/div[3]/div/div[1]/div[1]/input"));
        ElementUtil.inputValue(inputEle, keyWord);

        //3.点击搜索
        WebElement searchEle = driver.findElement(By.xpath("//*[@id=\"root\"]/div[1]/div[2]/div/div[3]/div/div[1]/button"));
        searchEle.click();
        log.info("正在搜索...");
        DelayUtil.sleepRangSecond(8, 12); //等待跳转 这个时间比较长

        //3.1页面矫正---可能出现提示是机器人
        String pageSource = driver.getPageSource();
        if (pageSource.contains("亲，请拖动下方滑块完成验证") && pageSource.contains("通过验证以确保正常访问")) {
            throw new RobotOperateException("被网站检查出是机器人");
        }
        log.info("搜素结果已经返回");

        //4.检索核心页面
        int order = 0;
        WebElement targetLtdElemet = null;
        WebElement pItem = driver.findElement(By.xpath("//*[@id=\"icbu-the-body-container\"]/div[1]/div[5]/div[3]"));
        List<WebElement> listItem = pItem.findElements(By.xpath("div[@data-aplus-no-clk=\"false\"]"));
        log.info("详情列表中需要分析的项数={}", listItem.size());
        for (WebElement item : listItem) {
            order++;

            //信息1处理
            String htmlOrder = "";
            List<WebElement> orderElements = item.findElements(By.xpath("div[2]/div[1]/a[3]"));
            if (!CollectionUtils.isEmpty(orderElements)) {
                htmlOrder = orderElements.get(0).getText();
            }

            //信息2处理
            String htmlCompanyName = "";
            List<WebElement> companyNameElements = item.findElements(By.xpath("div[2]/div[1]/a[4]"));
            if (!CollectionUtils.isEmpty(companyNameElements)) {
                htmlCompanyName = companyNameElements.get(0).getText();
            }

            if (htmlCompanyName.contains(companyName)) {
                targetLtdElemet = item;
                break;
            }
            log.info("排名在我前面,第{}名的companyname={},info={}", order, htmlCompanyName, htmlOrder);
        }

        if (targetLtdElemet == null) {
            throw new UnFindTargetException("没有发现目标点击项");
        }
        log.info("搜索关键字,目前在排名为={}", order);

        //5.点击查看详情按钮
        targetLtdElemet.click();
        DelayUtil.sleepRangMillis(800, 1500);

        //6.切换到第一个窗口
        DriverUtil.switchToTarget(driver, null, sessionIds);
        String currentUrl = driver.getCurrentUrl();
        if (currentUrl.startsWith("https://www.alibaba.com/product-detail")) {
            log.info("点击完成");
        }

        log.info("开始关闭部分窗口");


        //7.关闭最后一个tab
        DriverUtil.closeTab(driver);

        //8.切换到第一个窗口
        DriverUtil.switchToTarget(driver, sessionId, null);

        long costTime = System.currentTimeMillis() - startTime;
        log.info("调用耗时={}", costTime / 1000);

        return costTime;
    }

    public static void main(String[] args) {
        WebDriver driver = DriverUtil.getDriver("fdfdfd");
        AlibabaClickGridBoxService al = new AlibabaClickGridBoxService();
        al.reInitDriver(driver);

        al.batchClickGrid(40, "Table light", "Shenzhen Founder Industrial Co., Ltd");
        al.batchClickGrid(70, "Led table lamp", "Shenzhen Founder Industrial Co., Ltd");
        al.batchClickGrid(50, "Led desk lamp", "Shenzhen Founder Industrial Co., Ltd");
    }
}
